package com.focusai.efairy.network;

import android.support.annotation.Nullable;

import com.focusai.efairy.network.exception.NetworkException;


/**
 * Created by heqingbao on 2016/8/3.
 */
public class Response<T> {

    private T mResult;

    private final NetworkException mError;

    public Response(T result) {
        mResult = result;
        mError = null;
    }

    public Response(NetworkException error) {
        mResult = null;
        mError = error;
    }

    public T getResult() {
        return mResult;
    }

    public NetworkException getError() {
        return mError;
    }

    public boolean isSuccess() {
        return mError == null;
    }

    public static <T> Response<T> success(T result) {
        return new Response<T>(result);
    }

    public static <T> Response<T> error(NetworkException error) {
        return new Response<T>(error);
    }

    // 用于success=false并且仍需要解析data字段的情况，勿滥用！！！
    public void setResult(T result) {
        mResult = result;
    }

    public static abstract class Listener<T> {

        private Object mRequestTag;

        @Nullable
        protected Object getRequestTag() {
            return mRequestTag;
        }

        public void success(Object requestTag, T response) {
            mRequestTag = requestTag;
            if (!handledBefore()) {
                onSuccess(response);
                onFinish();
            }
        }

        public void fail(Object requestTag, NetworkException error) {
            mRequestTag = requestTag;
            if (!handledBefore()) {
                onFail(error);
                onFinish();
            }
        }

        protected boolean handledBefore() {
            return false;
        }

        protected abstract void onSuccess(T response);

        protected abstract void onFail(NetworkException exception);

        /**
         * 成功，失败都会调用到
         */
        protected void onFinish() {
        }

    }
}
